package group.sicher.core.utils;

import com.github.crab2died.ExcelUtils;
import group.sicher.core.exception.ResponseException;
import group.sicher.core.exception.base.SicherErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Created by bootvue@gmail.com
 * Date 2019-04-03 23:49
 * excel操作
 */
@Slf4j
public class ExcelUtil {
    /**
     * 导出excel
     *
     * @param datas  要导出的数据
     * @param header 头部
     * @param path   excel保存的位置
     * @return 文件名
     */
    public static String export(List<List<String>> datas, List<String> header, String path) {
        if (CollectionUtils.isEmpty(datas)) {
            return null;
        }

        String filename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomStringUtils.randomNumeric(5) + ".xlsx";

        try {
            ExcelUtils.getInstance().exportObjects2Excel(datas, header, path + "/" + filename);
            log.info("excel生成成功,文件名: {}", filename);
            return filename;
        } catch (IOException e) {
            log.error("excel生成失败: {}", e);
            throw new ResponseException(SicherErrorCode.EXPORT_ERROR);
        }
    }
}
